package com.oppo.service.impl;

import com.oppo.exception.BusinessException;
import com.oppo.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传下载预览业务接口实现层
 *
 * @author steve
 * @since 2022-01-29 20:11
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    /**
     * 文件保存路径
     */
    @Value("${file.upload.path}")
    private String path;

    private static final long MAX_FILE_SIZE = 1048576L;


    /**
     * 上传
     *
     * @param file 文件
     * @return {@link String}
     */
    @Override
    public String upload(@NotNull MultipartFile file) throws Exception {
        // 1.参数校验
        /*if (file == null) {
            return "文件为空，请重新上传";
        }*/

        long size = file.getSize();
        if (size > MAX_FILE_SIZE) {
            return "文件太大超过限定大小10Mb，无法上传";
        }

        // 2.获取文件流的信息如原生名称
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)) {
            return "上传的文件名不能为空";
        }
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String filePath = path + UUID.randomUUID().toString() + suffix;

        // 3.保存文件
        File dest = new File(filePath);

        // 3.1 判断文件路径是否存在
        if (!dest.getParentFile().exists()) {
            // 路径不存在则新建路径
            dest.getParentFile().mkdirs();
        }
        try {
            // 这种也行 Files.copy(file.getInputStream(), dest.toPath());
            // 下面这种也可以
            file.transferTo(dest);
        } catch (IOException e) {
            log.error("文件上传失败，请稍后再试");
            throw new BusinessException(500, "文件上传失败，请稍后再试");
        }

        // 4.返回前端的信息
        return "文件上传成功，路径为：" + path.replace("\\", "");
    }


    /**
     * 上传文件
     * @param file 文件
     * @return {@link Object}
     */
    @Override
    public String uploadFile(@NotNull MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)) {
            return "上传的文件名不能为空";
        }

        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String filePath = path + originalFilename.substring(0,index) + "-" + UUID.randomUUID().toString() + suffix;

        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
        outputStream.write(file.getBytes());
        outputStream.flush();
        outputStream.close();
        return "文件上传成功";

    }
}
